package de.micromata.cal;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
import java.util.Random;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.fortuna.ical4j.model.Calendar;

import org.apache.log4j.Logger;

/**
 * importing events from ical file and filter eventy, which starts today
 * open a random template and draw the description/summary of the event on the image
 * print image to response as outputstream
 */
public class ImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1781718579371045471L;
	private static Logger LOG = Logger.getRootLogger();
	private String absoluteFilesystemPath = null;
	private int cacheTime;
	private byte [] imageByteArray = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cacheParam = request.getParameter("cache");
		if (cacheParam != null && cacheParam.equals("off")) {
			cacheTime = -1;
		}
		//cacheTime = -1;
		// set header information
		response.setContentType("image/jpeg");
		response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
		response.setHeader("Pragma","no-cache"); //HTTP 1.0
		response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
		
		java.util.Calendar now = java.util.Calendar.getInstance();
		now.set(java.util.Calendar.HOUR_OF_DAY, now.get(java.util.Calendar.HOUR_OF_DAY));
		if (now.get(java.util.Calendar.MINUTE) != cacheTime) {
			cacheTime = now.get(java.util.Calendar.MINUTE);
			LOG.info("image port: "+request.getServerPort());
			absoluteFilesystemPath = getServletContext().getRealPath("/");
			String calendarFile = getInitParameter("calendarFile");
			boolean remoteFile = getInitParameter("remoteFile").equals("1") ? true : false;
			Calendar calendar = Utils.openIcal(calendarFile, remoteFile);
			//Calendar calendar = Utils.openIcal(absoluteFilesystemPath + "cal.ics", false);
			
			// open random template image or empty image
			//BufferedImage outImg = new BufferedImage(800, 480, 1); // empty image
			Random r = new Random();
			int random = r.nextInt(7) + 1;
			String filename = "img/template"+random+".png";
	
			BufferedImage bufferImg = null;
			try {
				bufferImg = ImageIO.read(new File(absoluteFilesystemPath+filename));
			} catch (IOException e2) {
				LOG.error("could not open template image: "+absoluteFilesystemPath+filename);
				e2.printStackTrace();
			}
			
			Drawing.drawContent(bufferImg, calendar);
			
			// send image to response as outputstream
			ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
			ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
			ImageOutputStream ios = ImageIO.createImageOutputStream(byteOutputStream);
			writer.setOutput(ios);
			ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
			iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			iwparam.setCompressionQuality(1f);
			writer.write(null, new IIOImage(bufferImg, null, null), iwparam);
			ios.flush();
			writer.dispose();
			ios.close();
	
	    imageByteArray = byteOutputStream.toByteArray();
	    OutputStream os = response.getOutputStream();
	    os.write(imageByteArray);
		} else {
			LOG.info("send cached image "+ cacheTime +": "+request.getServerPort());
			OutputStream os = response.getOutputStream();
	    os.write(imageByteArray);
		}
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
